<?php

require_once 'Base.php';

class UploadImage extends Base {
    public function upload(){
        $info=[
            'errorCode'=>10001,
            'msg'=>'图片上传失败',
            'data'=>[]
        ];
        if($_POST){
            if(!isset($_POST['mch_id'])){
                $info['msg']='请提交商户号';
                return json_encode($info);
            }
            if(!isset($_FILES['file'])){
                $info['msg']='请提交图片';
                return json_encode($info);
            }
            //上传图片
            $filename = $_FILES['file']['name'];
            //正则表达式匹配出上传文件的扩展名
            preg_match('|\.(\w+)$|', $filename, $ext);
            $ext = strtolower($ext[1]);
            $filename=time().'.'.$ext;
            $filePath=$this->uploadMediaPath.'/'.$filename;
            move_uploaded_file($_FILES["file"]["tmp_name"], $filePath);
            //请求media_id
            $requestParams=[
                'mch_id'=>$_POST['mch_id'],
                'media_hash'=>strtolower($this->hashMedia($filePath)),
                'sign_type'=>'HMAC-SHA256'
            ];
            $requestParams['sign']=$this->generateSign($requestParams);
            $requestParams['media']=new \CURLFile($filePath);
            $header= ["content-type:multipart/form-data"];

            $url="https://api.mch.weixin.qq.com/secapi/mch/uploadmedia";

            $response=$this->curlRequest($url,$requestParams,$header,true);

            if($response['return_code']=='SUCCESS'){
                $info['errorCode']=0;
                $info['msg']='上传成功';
                $info['data']=$response;
                return json_encode($info);
            }
            $info['msg']=$response['return_msg'];
        }
        return json_encode($info);
    }
}

echo (new UploadImage())->upload();